#ifndef __MUTEX_H__
#define __MUTEX_H__

#include <pthread.h>

class Mutex {
private:
    pthread_mutex_t* _ptr_mutex;

public:
    Mutex(pthread_mutex_t* ptr_mutex)
        : _ptr_mutex(ptr_mutex)
    {}

    Mutex(const pthread_mutex_t*& ptr_mutex) = delete;
    Mutex& operator=(const pthread_mutex_t*& ptr_mutex) = delete;

public:
    void lock() {
        if (_ptr_mutex != nullptr) {
            pthread_mutex_lock(_ptr_mutex);
        }
    }

    void unlock() {
        if (_ptr_mutex != nullptr) {
            pthread_mutex_unlock(_ptr_mutex);
        }
    }
};

// 模仿了STL中的lock_guard，使用了RAII的编程思想
class LockGuard {
private:
    Mutex mutex;

public:
    LockGuard(pthread_mutex_t* ptr_mutex)
        : mutex(ptr_mutex) // 调用了Mutex类的构造函数
    {
        mutex.lock();
    }

    ~LockGuard() {
        mutex.unlock();
    }

    LockGuard(const LockGuard& lg) = delete;
    LockGuard& operator=(const LockGuard& lg) = delete;

    LockGuard(LockGuard&& lg) = default;
    LockGuard& operator=(LockGuard&& lg) = default;
};

#endif